package com.cloudlead.web.server;

import com.cloudlead.common.lang.Configs;
import com.cloudlead.common.worker.ApiRegistry;
import com.cloudlead.common.worker.web.SimpleServer;
import com.cloudlead.common.worker.web.WorkerInfo;
import com.cloudlead.common.worker.web.WorkerManager;
import com.sun.enterprise.mgmt.transport.NetworkUtility;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.webapp.WebAppContext;

import java.io.IOException;

public class DashboardServer extends SimpleServer {
    public static final String DEFAULT_WEB_CONTEXT = "webContext";

    public DashboardServer(int serverPort) {
        this(null, serverPort);
    }

    public DashboardServer(String serverHost, int serverPort) {
        super(serverHost, 8081);
    }

    @Override
    protected void setContext(String contextPath) {
        context = new WebAppContext(Configs.getString("dashboard.webContext", DEFAULT_WEB_CONTEXT), contextPath);
        server.setHandler(context);
    }

    @Override
    public void start() throws Exception {
        super.start();

        WorkerInfo workerInfo = new WorkerInfo(serverHost, serverPort);
        if (StringUtils.isBlank(serverHost) || NetworkUtility.getAnyAddress().getHostAddress().equals(serverHost)) {
            try {
                String hostAddress = NetworkUtility.getFirstInetAddress().getHostAddress();
                workerInfo.setWorkerIp(hostAddress);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        WorkerManager.getInstance().joinGroup(workerInfo, springContext.getBean(ApiRegistry.class), true);
    }

    public static void main(String[] args) throws Exception {
        DashboardServer jettyServer = new DashboardServer(
                Integer.valueOf(Configs.getString("dashboard.server.port")));
        jettyServer.start();
    }
}
